<template>
  <div
    style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center"
  >
    <el-avatar
      :size="props.size"
      :shape="props.shape"
      :src="props.src"
      :src-set="props.srcSet"
      :alt="props.alt"
      :fit="props.fit"
      :style="getAvatarStyle()"
      @error="handleError"
    >
      <template v-if="!props.src && props.text">
        {{ props.text }}
      </template>
      <template v-else-if="!props.src && !props.text && props.icon">
        <el-icon :size="getIconSize()">
          <component :is="getIconComponent()" />
        </el-icon>
      </template>
      <template v-else-if="!props.src && !props.text && !props.icon">
        {{ getDefaultText() }}
      </template>
    </el-avatar>
  </div>
</template>

<script setup lang="ts">
import { computed, watchEffect } from 'vue';
import { ElAvatar, ElIcon } from 'element-plus';
import { User, Avatar } from '@element-plus/icons-vue';

const props = defineProps({
  size: {
    type: [Number, String],
    default: 'default'
  },
  shape: {
    type: String as () => 'circle' | 'square',
    default: 'circle'
  },
  src: {
    type: String,
    default: ''
  },
  srcSet: {
    type: String,
    default: ''
  },
  alt: {
    type: String,
    default: ''
  },
  fit: {
    type: String as () => 'fill' | 'contain' | 'cover' | 'none' | 'scale-down',
    default: 'cover'
  },
  icon: {
    type: String,
    default: ''
  },
  text: {
    type: String,
    default: ''
  },
  backgroundColor: {
    type: String,
    default: ''
  },
  textColor: {
    type: String,
    default: ''
  },
  borderColor: {
    type: String,
    default: ''
  },
  borderWidth: {
    type: [String, Number],
    default: 0
  }
});

const emit = defineEmits(['error']);

const iconComponents = {
  User,
  Avatar
};

const getAvatarStyle = () => {
  const style: Record<string, string> = {};

  if (props.backgroundColor) {
    style.backgroundColor = props.backgroundColor;
  }

  if (props.textColor) {
    style.color = props.textColor;
  }

  if (props.borderColor && props.borderWidth) {
    style.border = `${props.borderWidth}px solid ${props.borderColor}`;
  }

  return style;
};

const getIconSize = () => {
  if (typeof props.size === 'number') {
    return Math.floor(props.size * 0.5);
  }

  switch (props.size) {
    case 'large':
      return 20;
    case 'small':
      return 12;
    default:
      return 16;
  }
};

const getIconComponent = () => {
  if (props.icon && iconComponents[props.icon as keyof typeof iconComponents]) {
    return iconComponents[props.icon as keyof typeof iconComponents];
  }
  return User; // 默认图标
};

const getDefaultText = () => {
  // 如果没有提供文本，返回默认文本
  return 'U';
};

const handleError = (event: Event) => {
  emit('error', event);
};

// Props已就绪
</script>
